#include "MonitoringHistoryData.h"
#include "ui_MonitoringHistoryData.h"
#include "SnaillTcpClient.h"
#include <QAxObject>
#include <QFileDialog>
#include <QStandardPaths> // 添加这一行
#include <QMessageBox>
MonitoringHistoryData::MonitoringHistoryData(QWidget *parent,userModel*uModel) :
    QWidget(parent),
    ui(new Ui::MonitoringHistoryData),
    uModel(uModel),
    tabModel(this)
{
    ui->setupUi(this);
    ui->tableView->setModel(&tabModel);
    connect(SnaillTcpClient::instance(), &SnaillTcpClient::dataReceived, this, &MonitoringHistoryData::handleDataReceived);
    connect(ui->pushButton,&QPushButton::clicked,this,&MonitoringHistoryData::selectData);
    LOG_INFO("用户"+uModel.id+"查看了历史数据");
    connect(ui->pushButton_2,&QPushButton::clicked,this,&MonitoringHistoryData::getDataExcel);
}
void MonitoringHistoryData::handleDataReceived(const QByteArray &data)
{
    qDebug()<<"==+++=="<<data;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    QJsonObject jsonObj = jsonDoc.object();
    QString action = jsonObj["action"].toString();
    if(action=="selectAllData"){
        qDebug()<<"deviceList==="<<jsonObj;

        dataList =getDataList(data);
        tabModel.updateAllDeviceList(dataList);
    }else if (action=="selectReasonData") {
        dataList =getDataList(data);
        tabModel.updateAllDeviceList(dataList);
    }
}

void MonitoringHistoryData::getDataExcel()
{

    QString fileName = QFileDialog::getSaveFileName(ui->tableView, "保存", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), "Excel 文件(*.xls *.xlsx)");
        QAxObject *excel = new QAxObject;
        if (!excel->setControl("Excel.Application")) {
            QMessageBox::critical(this, "错误", "无法启动 Excel 应用程序");
            delete excel;
            return;
        }

        excel->dynamicCall("SetVisible (bool Visible)", "false");
        excel->setProperty("DisplayAlerts", false);
        QAxObject *workbooks = excel->querySubObject("WorkBooks");
        if (workbooks) {
            workbooks->dynamicCall("Add");
            QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
            if (workbook) {
                QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
                if (worksheet) {
                    // 写入表头
                    int colCount = ui->tableView->model()->columnCount();
                    int rowCount = ui->tableView->model()->rowCount();
                    for (int i = 0; i < colCount; ++i) {
                        QString columnName = ui->tableView->model()->headerData(i, Qt::Horizontal).toString();
                        QAxObject *cell = worksheet->querySubObject("Cells(int,int)", 1, i + 1);
                        cell->dynamicCall("SetValue(const QString&)", columnName);
                    }

                    // 写入数据
                    for (int i = 0; i < rowCount; ++i) {
                        for (int j = 0; j < colCount; ++j) {
                            QModelIndex index = ui->tableView->model()->index(i, j);
                            QString data = ui->tableView->model()->data(index).toString();
                            QAxObject *cell = worksheet->querySubObject("Cells(int,int)", i + 2, j + 1);
                            cell->dynamicCall("SetValue(const QString&)", data);
                        }
                    }

                    // 保存文件并关闭Excel
                    workbook->dynamicCall("SaveAs(const QString&)", fileName);
                    workbook->dynamicCall("Close()");
                    delete worksheet;
                }
                delete workbook;
            }
            delete workbooks;
        }
        excel->dynamicCall("Quit()");
        delete excel;

    LOG_INFO("用户"+uModel.id+"导出了历史数据");
}
void MonitoringHistoryData::showEvent(QShowEvent *event)
{
   // qDebug() << "页面显示，进入页面操作可在此处添加";
    QJsonObject jsonObj;
    jsonObj["action"] ="selectAllData";
    jsonObj["user_id"] =QString::number(uModel->id);
    if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
       //  qDebug() << "deviceList data sent successfully";

    } else {

        return ;
    }
    QWidget::showEvent(event);
}

void MonitoringHistoryData::selectData()
{
    QJsonObject jsonObj;
    jsonObj["action"] ="selectReasonData";
    jsonObj["user_id"] =QString::number(uModel->id);
     jsonObj["device_id"] =ui->lineEdit_3->text();
      jsonObj["startTime"] =ui->lineEdit->text();
       jsonObj["endTime"] =ui->lineEdit_2->text();
    if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
         qDebug() << "deviceList data sent successfully";

    } else {

        return ;
    }
}
QList<MonitoringDataModel> MonitoringHistoryData::getDataList(const QString &jsonString)
{
    QList<MonitoringDataModel> dataList;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
    if (jsonDoc.isObject()) {
        QJsonObject rootObject = jsonDoc.object();
        if (rootObject.contains("data") && rootObject["data"].isArray()) {
            QJsonArray jsonArray = rootObject["data"].toArray();
            for (const QJsonValue &value : jsonArray) {
                if (value.isObject()) {
                    QJsonObject deviceObject = value.toObject();
                    MonitoringDataModel data;
                    data.id = deviceObject["id"].toString();
                    data.user_id = deviceObject["user_id"].toString();
                    data.device_id = deviceObject["device_id"].toString();
                    data.timestamp = deviceObject["timestamp"].toString();
                    data.temperature = deviceObject["temperature"].toString();
                    data.humidity = deviceObject["humidity"].toString();
                    data.light = deviceObject["light"].toString();
                    data.co2 = deviceObject["co2"].toString();
                    data.pressure = deviceObject["pressure"].toString();
                    dataList.append(data);
                }
            }
        }
    }
    return dataList;
}

MonitoringHistoryData::~MonitoringHistoryData()
{
    delete ui;
}
